import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class TestHeap {

    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {  //创建一个大根堆
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    public void shiftDown(int parent,int len) {  // 向下调整
        int child = 2*parent+1;
        while (child < len) {
            if ((child+1) < len && (elem[child] < elem[child+1])) {
                child = child +1;
            }
            if (elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

    public void offer(int val) { //插入一个元素，插入完依然是大根堆
        if (isFull()) {
            //要进行扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        //此时要进行向上调整
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int parent = (child-1) / 2;
        while (child > 0) {
            if (child > parent) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1) /2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public void pop() {
        //判断是否为空
        if (isEmpty()) {
            return;
        }
        int swap = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = swap;
        usedSize--;
        //向下调整
        int len = usedSize;
        int parent = 0;
        int child = 2*parent + 1;
        while (child < len) {
            if (elem[child] < elem[child+1] && (child+1) < len) {
                child++;
            }
            if (elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent + 1;
            }else {
                break;
            }
        }

    }

    private boolean isEmpty() {
        return usedSize == 0;
    }
}
